package com.bree.erp.service.stateless;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.bree.erp.entity.Project;
import com.bree.erp.service.ProjectService;

@Stateless
public class ProjectServiceBean implements ProjectService {

	@PersistenceContext()
	private EntityManager em;
	
	public ProjectServiceBean() {
		
	}
	
	public ProjectServiceBean(EntityManager em) {
		this.em = em;
	}

	@Override
	public Project create(String code, String description) {
		
		Project project = new Project();
		
		project.setCode(code);
		project.setDescription(description);
		
		em.persist(project);
		
		return project;
	}

	@Override
	public List<Project> list() {
		TypedQuery<Project> query = em.createNamedQuery(Project.QUERY_SELECT_ALL_PROJECT, Project.class);
		return query.getResultList();
	}

	@Override
	public Project read(Long id) {
		
		return em.find(Project.class, id);
	}

	@Override
	public Project update(Long id, String code, String description) {
		
		Project project = this.read(id);
		
		project.setCode(code);
		project.setDescription(description);
		
		return project;
	}

	@Override
	public Project delete(Long id) {
		Project project = this.read(id);
		
		if(project != null) {
			em.remove(project);
		}
		
		return project;
	}

	@Override
	public Project findByCode(String code) {
		TypedQuery<Project> query = em.createNamedQuery(Project.QUERY_FIND_PROJECT_BY_CODE, Project.class)
				.setParameter("code", code);
				
		return query.getSingleResult();
	}

}
